/**
 * 工具函数
 */

/**
 * 检查API客户端是否已初始化
 */
function checkApiReady() {
  if (!window.api) {
    console.error('[Utils] API客户端未初始化');
    showToast('系统错误：API客户端未初始化', 'error');
    return false;
  }
  return true;
}

/**
 * 等待API客户端初始化
 */
async function waitForApi(maxRetries = 10) {
  let retryCount = 0;
  while (!window.api && retryCount < maxRetries) {
    console.log('[Utils] 等待API客户端初始化...');
    await new Promise(resolve => setTimeout(resolve, 100));
    retryCount++;
  }
  return !!window.api;
}

/**
 * 显示消息提示
 */
function showToast(message, type = 'info', duration = 3000) {
  const toast = document.getElementById('toast');
  const iconElement = toast.querySelector('.toast-icon');
  const messageElement = toast.querySelector('.toast-message');
  
  // 设置图标
  let iconClass = 'fas fa-info-circle';
  switch (type) {
    case 'success':
      iconClass = 'fas fa-check-circle';
      break;
    case 'error':
      iconClass = 'fas fa-exclamation-circle';
      break;
    case 'warning':
      iconClass = 'fas fa-exclamation-triangle';
      break;
  }
  
  iconElement.className = `toast-icon ${iconClass}`;
  messageElement.textContent = message;
  
  // 设置样式类
  toast.className = `toast ${type}`;
  
  // 显示提示
  toast.classList.add('show');
  
  // 自动隐藏
  setTimeout(() => {
    toast.classList.remove('show');
  }, duration);
}

/**
 * 显示模态对话框
 */
function showModal(modalId) {
  const modal = document.getElementById(modalId);
  if (modal) {
    modal.classList.add('show');
    // 聚焦到第一个输入框
    const firstInput = modal.querySelector('input, select, textarea');
    if (firstInput) {
      setTimeout(() => firstInput.focus(), 100);
    }
  }
}

/**
 * 关闭模态对话框
 */
function closeModal(modalId) {
  const modal = document.getElementById(modalId);
  if (modal) {
    modal.classList.remove('show');
    // 清空表单
    const forms = modal.querySelectorAll('form');
    forms.forEach(form => form.reset());
  }
}

/**
 * 格式化时间
 */
function formatTime(isoString) {
  if (!isoString) return '未知';
  
  try {
    const date = new Date(isoString);
    const now = new Date();
    const diffMs = now - date;
    const diffMins = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMins / 60);
    const diffDays = Math.floor(diffHours / 24);
    
    if (diffMins < 1) {
      return '刚刚';
    } else if (diffMins < 60) {
      return `${diffMins}分钟前`;
    } else if (diffHours < 24) {
      return `${diffHours}小时前`;
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      return date.toLocaleDateString('zh-CN');
    }
  } catch (error) {
    return '未知';
  }
}

/**
 * 检查环境配置是否有效
 */
function hasValidConfig(config) {
  return config && typeof config === 'string' && config.trim().length > 0;
}

/**
 * 获取环境配置状态文本
 */
function getEnvironmentConfigStatus(config) {
  if (!hasValidConfig(config)) {
    return '<div class="config-status unconfigured"><i class="fas fa-exclamation-circle"></i> 未配置</div>';
  }
  
  // 解析配置行，提取有效的域名映射
  const lines = config.split('\n').filter(line => {
    const trimmed = line.trim();
    return trimmed && !trimmed.startsWith('#');
  });
  
  if (lines.length === 0) {
    return '<div class="config-status unconfigured"><i class="fas fa-exclamation-circle"></i> 未配置</div>';
  }
  
      // 显示具体的配置内容（用户输入格式：IP地址 域名）
    const mappings = lines.slice(0, 3).map((line, index) => {
      const parts = line.trim().split(/\s+/);
      if (parts.length >= 2) {
        const target = parts[0];  // IP地址
        const domain = parts[1];  // 域名
        return `<div class="config-mapping">
          <i class="fas fa-arrow-right" style="font-size: 0.7em; color: var(--gray-400); margin: 0 4px;"></i>
          ${escapeHtml(target)} → ${escapeHtml(domain)}
        </div>`;
      }
      return `<div class="config-mapping">
        <i class="fas fa-arrow-right" style="font-size: 0.7em; color: var(--gray-400); margin: 0 4px;"></i>
        ${escapeHtml(line.trim())}
      </div>`;
    }).join('');
  
  // 如果有更多规则，显示省略号
  const moreText = lines.length > 3 ? `<div class="config-more">
    <i class="fas fa-ellipsis-h" style="margin-right: 4px;"></i>
    共${lines.length}个规则
  </div>` : '';
  
  return `<div class="config-content">
    <div class="config-header">
      <i class="fas fa-check-circle" style="color: var(--success-color); margin-right: 4px;"></i>
      已配置
    </div>
    ${mappings}${moreText}
  </div>`;
}

/**
 * 获取简洁的配置显示（新设计）
 */
function getSimpleConfigDisplay(config, envName, projectId) {
  if (!hasValidConfig(config)) {
    return '<span class="config-simple-text">未配置</span>';
  }
  
  // 解析配置行，提取有效的域名映射
  const lines = config.split('\n').filter(line => {
    const trimmed = line.trim();
    return trimmed && !trimmed.startsWith('#');
  });
  
  if (lines.length === 0) {
    return '<span class="config-simple-text">未配置</span>';
  }
  
  if (lines.length === 1) {
    // 只有一个配置，直接显示
    const parts = lines[0].trim().split(/\s+/);
    if (parts.length >= 2) {
      return `<span class="config-simple-text">${escapeHtml(parts[0])}：${escapeHtml(parts[1])}</span>`;
    }
    return `<span class="config-simple-text">${escapeHtml(lines[0].trim())}</span>`;
  }
  
  // 多个配置，显示第一个+下拉箭头
  const firstLine = lines[0].trim();
  const parts = firstLine.split(/\s+/);
  const firstDisplay = parts.length >= 2 ? `${escapeHtml(parts[0])}：${escapeHtml(parts[1])}` : escapeHtml(firstLine);
  
  // 构建下拉面板内容
  const dropdownItems = lines.map(line => {
    const parts = line.trim().split(/\s+/);
    if (parts.length >= 2) {
      return `<div class="config-dropdown-item">${escapeHtml(parts[0])} → ${escapeHtml(parts[1])}</div>`;
    }
    return `<div class="config-dropdown-item">${escapeHtml(line.trim())}</div>`;
  }).join('');
  
  return `
    <div class="config-dropdown-wrapper" onmouseenter="showConfigDropdown(this)" onmouseleave="hideConfigDropdown(this)">
      <span class="config-simple-text">${firstDisplay}</span>
      <i class="fas fa-chevron-down config-dropdown-arrow"></i>
      <div class="config-dropdown-panel">
        <div class="config-dropdown-content">
          ${dropdownItems}
        </div>
      </div>
    </div>
  `;
}

/**
 * 生成项目卡片HTML
 */
function createProjectCard(project) {
  const isActive = project.activeEnvironment !== null;
  
  return `
    <div class="project-card ${isActive ? 'active' : ''}" data-project-id="${project.id}">
      <div class="project-header-simple">
        <h3 class="project-title">${escapeHtml(project.name)}</h3>
        <button class="btn btn-text btn-sm" onclick="editProject('${project.id}')" title="配置项目">
          <i class="fas fa-cog"></i>
        </button>
      </div>
      
      <div class="project-environments-simple">
        <div class="environment-row-simple">
          <div class="environment-left">
            <span class="environment-name-simple">测试环境</span>
            ${getSimpleConfigDisplay(project.environments.test, 'test', project.id)}
          </div>
          <div class="environment-right">
            ${hasValidConfig(project.environments.test) 
              ? `<button class="btn btn-sm ${project.activeEnvironment === 'test' ? 'btn-success' : 'btn-outline'}" 
                   onclick="toggleEnvironment('${project.id}', 'test')">
                   ${project.activeEnvironment === 'test' ? '已激活' : '激活'}
                 </button>`
              : `<button class="btn btn-sm btn-outline" onclick="editProject('${project.id}')">配置</button>`
            }
          </div>
        </div>
        
        <div class="environment-row-simple">
          <div class="environment-left">
            <span class="environment-name-simple">生产环境</span>
            ${getSimpleConfigDisplay(project.environments.production, 'production', project.id)}
          </div>
          <div class="environment-right">
            ${hasValidConfig(project.environments.production) 
              ? `<button class="btn btn-sm ${project.activeEnvironment === 'production' ? 'btn-success' : 'btn-outline'}" 
                   onclick="toggleEnvironment('${project.id}', 'production')">
                   ${project.activeEnvironment === 'production' ? '已激活' : '激活'}
                 </button>`
              : `<button class="btn btn-sm btn-outline" onclick="editProject('${project.id}')">配置</button>`
            }
          </div>
        </div>
        
        ${project.customRules && project.customRules.length > 0 
          ? project.customRules.map(rule => `
              <div class="environment-row-simple">
                <div class="environment-left">
                  <span class="environment-name-simple">${escapeHtml(rule.label)}</span>
                  ${getSimpleConfigDisplay(rule.value, `custom:${rule.id}`, project.id)}
                </div>
                <div class="environment-right">
                  <button class="btn btn-sm ${project.activeEnvironment === `custom:${rule.id}` ? 'btn-success' : 'btn-outline'}" 
                     onclick="toggleCustomRule('${project.id}', '${rule.id}')">
                     ${project.activeEnvironment === `custom:${rule.id}` ? '已激活' : '激活'}
                  </button>
                </div>
              </div>
            `).join('')
          : ''
        }
      </div>
    </div>
  `;
}

/**
 * 显示配置下拉面板
 */
window.showConfigDropdown = function(element) {
  const panel = element.querySelector('.config-dropdown-panel');
  if (panel) {
    panel.style.display = 'block';
    // 添加一个小延迟以确保动画效果
    setTimeout(() => {
      panel.style.opacity = '1';
      panel.style.transform = 'translateY(0)';
    }, 10);
  }
};

/**
 * 隐藏配置下拉面板
 */
window.hideConfigDropdown = function(element) {
  const panel = element.querySelector('.config-dropdown-panel');
  if (panel) {
    panel.style.opacity = '0';
    panel.style.transform = 'translateY(-8px)';
    // 等待动画完成后隐藏
    setTimeout(() => {
      panel.style.display = 'none';
    }, 200);
  }
};

/**
 * 获取环境状态文本
 */
function getEnvironmentStatusText(activeEnvironment) {
  if (!activeEnvironment) {
    return '未激活';
  }
  
  switch (activeEnvironment) {
    case 'test':
      return '测试环境';
    case 'production':
      return '生产环境';
    default:
      if (activeEnvironment.startsWith('custom:')) {
        return '自定义规则';
      }
      return '未知状态';
  }
}

/**
 * HTML转义
 */
function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

/**
 * 复制文本到剪贴板
 */
async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    showToast('已复制到剪贴板', 'success');
  } catch (error) {
    console.error('复制失败:', error);
    showToast('复制失败', 'error');
  }
}

/**
 * 确认对话框
 */
function confirm(message, title = '确认操作') {
  return new Promise((resolve) => {
    const modal = document.createElement('div');
    modal.className = 'modal show';
    modal.innerHTML = `
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title">${escapeHtml(title)}</h3>
        </div>
        <div class="modal-body">
          <p>${escapeHtml(message)}</p>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" onclick="this.closest('.modal').remove(); window.confirmResolve(false)">取消</button>
          <button class="btn btn-primary" onclick="this.closest('.modal').remove(); window.confirmResolve(true)">确定</button>
        </div>
      </div>
    `;
    
    document.body.appendChild(modal);
    
    window.confirmResolve = resolve;
  });
}

/**
 * 提示输入对话框
 */
function prompt(message, defaultValue = '', title = '输入') {
  return new Promise((resolve) => {
    const modal = document.createElement('div');
    modal.className = 'modal show';
    modal.innerHTML = `
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title">${escapeHtml(title)}</h3>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label class="form-label">${escapeHtml(message)}</label>
            <input type="text" class="form-input" id="promptInput" value="${escapeHtml(defaultValue)}">
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" onclick="this.closest('.modal').remove(); window.promptResolve(null)">取消</button>
          <button class="btn btn-primary" onclick="window.promptSubmit()">确定</button>
        </div>
      </div>
    `;
    
    document.body.appendChild(modal);
    
    const input = modal.querySelector('#promptInput');
    input.focus();
    input.select();
    
    window.promptResolve = resolve;
    window.promptSubmit = () => {
      const value = input.value.trim();
      modal.remove();
      resolve(value || null);
    };
    
    // 回车提交
    input.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        window.promptSubmit();
      }
    });
  });
}

/**
 * 防抖函数
 */
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

/**
 * 节流函数
 */
function throttle(func, limit) {
  let inThrottle;
  return function() {
    const args = arguments;
    const context = this;
    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

/**
 * 格式化文件大小
 */
function formatFileSize(bytes) {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

/**
 * 验证域名配置格式
 */
function validateDomainConfig(config) {
  if (!config || typeof config !== 'string') {
    return { valid: false, error: '配置不能为空' };
  }
  
  const lines = config.split('\n').filter(line => line.trim());
  if (lines.length === 0) {
    return { valid: false, error: '配置不能为空' };
  }
  
  const errors = [];
  
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim();
    
    // 跳过注释行
    if (line.startsWith('#')) {
      continue;
    }
    
    const parts = line.split(/\s+/);
    if (parts.length < 2) {
      errors.push(`第 ${i + 1} 行格式错误，应为：域名 IP地址`);
      continue;
    }
    
    const domain = parts[0];
    const target = parts[1];
    
    // 简单的域名格式检查
    if (!/^[a-zA-Z0-9.-]+$/.test(domain)) {
      errors.push(`第 ${i + 1} 行域名格式错误：${domain}`);
    }
    
    // 简单的目标格式检查
    if (!/^[a-zA-Z0-9.-:]+$/.test(target)) {
      errors.push(`第 ${i + 1} 行目标格式错误：${target}`);
    }
  }
  
  if (errors.length > 0) {
    return {
      valid: false,
      error: '配置格式验证失败',
      details: errors
    };
  }
  
  return { valid: true };
}

/**
 * 获取URL参数
 */
function getUrlParameter(name) {
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get(name);
}

/**
 * 设置URL参数
 */
function setUrlParameter(name, value) {
  const urlParams = new URLSearchParams(window.location.search);
  if (value) {
    urlParams.set(name, value);
  } else {
    urlParams.delete(name);
  }
  const newUrl = window.location.pathname + '?' + urlParams.toString();
  window.history.replaceState({}, '', newUrl);
}

/**
 * 深拷贝对象
 */
function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  
  if (obj instanceof Date) {
    return new Date(obj.getTime());
  }
  
  if (obj instanceof Array) {
    return obj.map(item => deepClone(item));
  }
  
  if (typeof obj === 'object') {
    const cloned = {};
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        cloned[key] = deepClone(obj[key]);
      }
    }
    return cloned;
  }
  
  return obj;
}

// 全局错误处理
window.addEventListener('error', (event) => {
  console.error('全局错误:', event.error);
  showToast('发生了一个错误，请查看控制台了解详情', 'error');
});

window.addEventListener('unhandledrejection', (event) => {
  console.error('未处理的Promise拒绝:', event.reason);
  showToast('操作失败，请重试', 'error');
});